<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function __construct(){
		parent::__construct();
		$this->load->library('session');
		//		$this->load->helper('cookie');
		//		$this->session->set_userdata('user_id','');
		//		$this->session->set_userdata('pass_id','');
		//		$this->session->set_userdata('logged_in','');
		$this->load->library("my_layout");
		$this->load->helper('form');
		$this->my_layout->setLayout("layout/layout");
		$this->load->library("form_validation");
		$this->load->model('member_model');
		$this->load->model('app_model');
		//		$this->load->model('member_model');
		//		$this->my_layout_diary->setLayout("layout/layout_diary");
	}
	private $limit = 9;
	private $count_tmp = 0;
	public function index(){
		//echo $_SERVER['HTTP_HOST']; //lay ten domain duoc go vao address
		//		$this->load->model('danhba_cat_model');
		//		$danhba['danhba'] = $this->danhba_cat_model->getAllDanhBa();
		$this->load->model('admin_model');
		$data['images'] = $this->admin_model->getHomeImage();
		$this->my_layout->view('index',$data);
	}
	public function langguagevi(){
		$url = $_SERVER['HTTP_REFERER'] ;
		$this->session->set_userdata('lang', 'vi');
		redirect($url,'post',false);
	}
	public function langguageeng(){
		$url = $_SERVER['HTTP_REFERER'] ;
		$this->session->set_userdata('lang', 'eng');
		redirect($url,'post',false);
	}
	public function login(){
		if(!$this->checkLogin()){
			$this->session->set_userdata('user_id', '');
			$this->session->set_userdata('pass_id', '');
			$this->session->set_userdata('logged_in', false);
			$this->form_validation->set_rules('user_id', 'Username','trim|required|min_length[6]|max_length[20]|xss_clean');
			$this->form_validation->set_rules('pass_id', 'Password','trim|required|min_length[6]|max_length[20]|xss_clean');
			$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
			if($this->form_validation->run()){
				$this->form_validation->set_rules('user_id', 'Username','callback_callbackCheckLogin');
				$this->form_validation->set_message('callbackCheckLogin', 'Username or Password not match. Please try again!');
				if($this->form_validation->run()){
					$this->session->set_userdata('user_id', $this->input->post('user_id'));
					$this->session->set_userdata('pass_id', md5('ThanhNV'.$this->input->post('pass_id')));
					$this->session->set_userdata('logged_in', true);
					//login thanh cong goi toi view cho xem 3 loai mat hang la new product, new onsale va kho hang
					//cho nay phan trang co 3 loai va phan trang cho 3 loai san pham
					
					$this->my_layout->view('html/catlogin',$this->loadMemberData());
//					$this->my_layout->view('member/newproduct');
//					$this->my_layout->view('member/newdesign');
//					$this->my_layout->view('member/storecate');
				}else{
					$this->my_layout->view('html/login');
				}
			}else{
				$this->my_layout->view('html/login');
			}
		}else{
			//login thanh cong goi toi view cho xem 3 loai mat hang la new product, new onsale va kho hang
			//cho nay phan trang co 3 loai va phan trang cho 3 loai san pham
			$this->my_layout->view('html/catlogin',$this->loadMemberData());
//			$this->my_layout->view('member/newproduct');
//			$this->my_layout->view('member/newdesign');
//			$this->my_layout->view('member/storecate');
		}
	}
	private function loadMemberData(){
		$data['newproduct'] = $this->member_model->showMemberProduct(11);
		$data['newdesign'] = $this->member_model->showMemberProduct(12);
		$data['storecate'] = $this->member_model->showMemberProduct(13);
		return $data;
	}
	public function callbackCheckLogin(){
		$user_id = $this->input->post('user_id');
		$pass_id = $this->input->post('pass_id');

		$check = $this->member_model->checkUser($user_id,md5('ThanhNV'.$pass_id));
		return $check;
	}
	public function checkLogin(){
		if (isset($this->session->userdata['logged_in'])){
			if ($this->session->userdata['logged_in']){

				$check = $this->member_model->checkUser($this->session->userdata['user_id'],$this->session->userdata['pass_id']);
				if ($check)return true;
				return false;
			}else return false;
		}else{
			$this->session->set_userdata('logged_in', false);
			return false;
		}
	}
	public function logout(){
		//		$this->session->sess_destroy();
		$this->session->set_userdata('logged_in',false);
		$this->index();
	}
	public function regist(){
		$this->my_layout->view('html/regist');
	}
	//	public function captcha(){
	//		$this->load->view('html/captcha');
	//	}
	public function search(){
		$this->load->helper('url');
		$this->load->library('pagination');
		if($this->uri->segment(4) == FALSE)
			$offset = 0;
		else
			$offset = $this->uri->segment(4);
		$ref = $this->input->post('cond_search');
		if (trim($ref)==''){
			$ref = $this->uri->segment(3);
			if (trim($ref)=='')
				redirect('welcome/index');
		}
		if ($this->checkLogin()){
			$data['subcate'] = $this->member_model->searchMember($ref,$this->limit, $offset);
			$total = $this->member_model->countMember($ref);
		}else{
			$data['subcate'] = $this->member_model->searchNotMember($ref,$this->limit, $offset);
			$total = $this->member_model->countNotMember($ref);
		}
		$data['name'] = 'Search Result';
		
		$config['base_url'] = site_url('welcome/search/'.$ref.'/');
 		
 		$config['total_rows'] = $total;
 		$config['per_page'] = $this->limit;
 		$config['uri_segment'] = 4;
		$this->pagination->initialize($config);
		$this->my_layout->view('html/catcommon',$data);
		
	}
	public function search1(){
		$this->load->helper('url');
		$this->form_validation->set_rules('cond_search', 'Condition Search','trim|required|min_length[5]|max_length[100]|xss_clean');
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
		if($this->form_validation->run()){
			$ref = $this->input->post('cond_search');
			$this->load->library('pagination');
			if ($this->checkLogin()){
				//Get Offset		
				if($this->uri->segment(3) == FALSE)
					$offset = 0;
				else
					$offset = $this->uri->segment(3);	
				//tim thong tin co nhung san pham can login
				$data['subcate'] = $this->member_model->searchMember($ref,9,$offset);
				$data['name'] = 'Search Result';
				
				
		
				//Set Config Pagination
				$config['base_url'] = site_url('welcome/search/');
		 		$total = $this->member_model->count_condition();
		 		$config['total_rows'] = $total;
		 		$config['per_page'] = 9;
		 		
				$config['uri_segment'] = 3;
				$this->pagination->initialize($config);
				$this->my_layout->view('html/catcommon',$data);
			}else{
				//chi tim nhung san pham ko duoc login 
				$data = $this->member_model->searchNotMember($ref,10,0);
				$this->my_layout->view('html/catcommon',$data);
			}
		}else {
			$this->my_layout->view('index');
		}
	}
	public function searchPageIgnit(){
		$condition = $this->input->post('cond_search');
		$this->load->helper('url');		
		
		//Get Offset		
		if($this->uri->segment(3) == FALSE)
			$offset = 0;
		else
			$offset = $this->uri->segment(3);
		//Load data		
		if ($this->checkLogin()){
			$data['subcate'] = $this->member_model->searchMember($condition,$this->limit, $offset);
			
		}else{
			$data['subcate'] = $this->member_model->searchNotMember($condition,$this->limit, $offset);
		}
		
		//Declare CodeIgniter Pagination
		$this->load->library('pagination');
		
		//Set Config Pagination
		$config['base_url'] = site_url('welcome/searchPageIgnit/');
		$total = $this->member_model->count_condition();
 		$config['total_rows'] = $total;
 		$config['per_page'] = $this->limit;
 		
		$config['uri_segment'] = 3;
		$this->pagination->initialize($config);
		
		$data['name'] = 'Search Result';
		$this->my_layout->view('html/catcommon',$data);
	}
	public function test(){
		echo 'test';
	}
	public function getDanhBaById($ref=NULL,$offset=null){
		$this->load->library('pagination');
		$this->load->helper('url');
		$this->load->model('danhba_model');
		//Get Offset
		if($this->uri->segment(4) == FALSE)
			$offset = 0;
		else
			$offset = $this->uri->segment(4);
		$data['danhba'] = $this->danhba_model->get_paged_list($this->limit,$offset,$ref);
		//Set Config Pagination
		$config['base_url'] = site_url('welcome/getDanhBaById/'.$ref.'/');
		$total = $this->danhba_model->count_AllById($ref);
		$config['total_rows'] = $total['0']['total'];
		$config['per_page'] = $this->limit;

		$config['uri_segment'] = 4;
		$this->pagination->initialize($config);
		$this->my_layout->view('danhba',$data);
	}
	public function getCatById($ref=NULL,$offset=null){
		if ($this->checkLogin()){
			$this->load->helper('url');		
		
			//Get Offset		
			if($this->uri->segment(4) == FALSE)
				$offset = 0;
			else
				$offset = $this->uri->segment(4);
			//Load data		
			$data['subcate'] =$this->member_model->getSubcateId($ref,$this->limit, $offset);
			
			//Declare CodeIgniter Pagination
			$this->load->library('pagination');
			
			//Set Config Pagination
			$config['base_url'] = site_url('welcome/getCatById/'.$ref);
	 		$config['total_rows'] = $this->member_model->count_all($ref);
	 		$config['per_page'] = $this->limit;
	 		
	 		$config['full_tag_open'] = '<p>';
			$config['full_tag_close'] = '</p>';
			
	 		$config['first_link'] = 'First';
	 		$config['first_tag_open'] = '<div>';
	 		$config['first_tag_close'] = '</div>';
	 		
	 		$config['last_link'] = 'Last';
	 		$config['last_tag_open'] = '<div>';
	 		$config['last_tag_close'] = '</div>';
	 		
			$config['uri_segment'] = 4;
			$this->pagination->initialize($config);
			
			if ($ref == 11){
				$data['name'] = 'New Product';
			}elseif ($ref == 12){
				$data['name'] = 'New Design';
			}else{
				$data['name'] = 'Categories Store';
			}
			
			$this->my_layout->view('html/catmember',$data);
//			$this->my_layout->view('html/catloginid');
		}else{
			$data['error'] = '<div class=error>Please, Login to view products </div>';
			$this->my_layout->view('html/login',$data);
		}
	}
	public function callbackcheck_captcha(){
		$word = $this->session->userdata('word');
		$wordconf = $this->input->post('numcapcha_regist_id');
		if(strtoupper($word) == strtoupper($wordconf)){
			return true;
		}else{
			return false;
		}
	}
	public function registMember(){
		$this->load->helper('date');
		$this->form_validation->set_rules('user_regist_id', 'Username','trim|required|min_length[6]|max_length[20]|xss_clean');
		$this->form_validation->set_rules('pass_regist_id', 'Password','trim|required|min_length[6]|max_length[20]|xss_clean');
		$this->form_validation->set_rules('prepass_regist_id', 'PrePassword','trim|matches[pass_regist_id]|xss_clean');
		$this->form_validation->set_rules('phone_regist_id', 'Phone','trim|required|numeric|min_length[8]|max_length[11]|xss_clean');
		$this->form_validation->set_rules('email_regist_id', 'Email','trim|required|valid_email|max_length[100]|xss_clean');
		$this->form_validation->set_rules('address_regist_id', 'Address','trim|required|min_length[6]|max_length[100]|xss_clean');
		$this->form_validation->set_rules('numcapcha_regist_id', 'Capcha','trim|required|exact_length[10]|callback_callbackcheck_captcha|xss_clean');
		$this->form_validation->set_message('callbackcheck_captcha', 'Number input not match image. Please try again!');
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
		if($this->form_validation->run()){
			if (!$this->checkMemberUserIdExist()){
				if (!$this->checkMemberEmailExist($this->input->post('email_regist_id'))){
					//save to db
					$key_regist = md5('ThanhNguyenVanWelcome').md5($this->input->post('pass_regist_id'));
					$ref = array(
								'user_id'		=>	$this->input->post('user_regist_id'),
								'pass_id'		=>	md5('ThanhNV'.$this->input->post('pass_regist_id')),
								'email'			=>	$this->input->post('email_regist_id'),
								'level'			=>	1,
								'phone'			=>	$this->input->post('phone_regist_id'),
								'birthday'		=>	$this->input->post('birthday_regist_id'),
								'address'		=>	$this->input->post('address_regist_id'),
								'delete_flag'	=>	1,
								'key_regist'	=>	$key_regist,
								'date_regist'	=>	date('Y-m-d H:i:s',now()),
								'update_date'	=>	date('Y-m-d H:i:s',now())
					);
					if ($this->saveDBNewUser($ref)){
						//	send mail
						if ($this->sendmail_smtp($ref,2))
						$this->my_layout->view('html/registsuccess');
						else echo "error mail send please try again! ";
					}else{
						$err['error']="<div class=error> Error save data to db, Please try again </div>";
						$this->my_layout->view('html/regist',$err);
					}
				}else{
					$err['error']="<div class=error> Email exist, Please choose function forgot password</div>";
					$this->my_layout->view('html/regist',$err);
				}
			}else{
				$err['error']="<div class=error>Username exist, Please change other user</div>";
				$this->my_layout->view('html/regist',$err);
			}
		}else{
			$this->my_layout->view('html/regist');
		}
	}
	
	public function checkMemberUserIdExist(){

		$check = $this->member_model->checkExistUser($this->input->post('user_regist_id'));
		return $check;
	}
	public function checkMemberEmailExist($email = null){

		$check = $this->member_model->checkExistEmail($email);
		return $check;
	}
	public function saveDBNewUser($data = null){

		$check = $this->member_model->saveUserNew($data);
		return $check;
	}
	public function resetUserPass(){
		echo 'Not support ';
		//$this->my_layout->view('html/forgotpass');
	}
	public function callbackcheck_captcha1(){
		$word = $this->session->userdata('word');
		$wordconf = $this->input->post('numcapcha_forgot_id');
		if(strtoupper($word) == strtoupper($wordconf)){
			return true;
		}else{
			return false;
		}
	}
	public function recoverPassEmail(){
		$this->form_validation->set_rules('email_forgot_id', 'Email','trim|required|valid_email|max_length[100]|xss_clean');
		$this->form_validation->set_rules('numcapcha_forgot_id', 'Capcha','trim|required|exact_length[10]|callback_callbackcheck_captcha1|xss_clean');
		$this->form_validation->set_message('callbackcheck_captcha1', 'Number input not match image. Please try again!');
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
		if($this->form_validation->run()){
			if ($this->checkMemberEmailExist($this->input->post('email_forgot_id'))){
				if (!$this->checkRecoverMail($this->input->post('email_forgot_id'))){
					$check = $this->member_model->updateUserPassForgot($this->input->post('email_forgot_id'));
					$data = $this->member_model->getUserForgot($this->input->post('email_forgot_id'));
					if ($this->sendmail_smtp($data[0],1)){
						$this->my_layout->view('html/fogotreport');
						//redirect(base_url());
					}else{
						echo "<script type='text/javascript'>alert('error mail send please try again! ') </script>";
					}
				}else{
					echo "<script type='text/javascript'>alert('Error! email have been recover! please check your email: ".$this->input->post('email_forgot_id')."') </script>";
				}
			}else{
				echo "<script type='text/javascript'>alert('error email not exist ! ') </script>";
			}
		}else {
			$this->my_layout->view('html/forgotpass');
		}
	}
	public function checkRecoverMail($email = null){
		$check = $this->member_model->checkExistRecoverMail($email);
		return $check;
	}
	public function confirmRegist($keyregist = null,$user = null){

		$check = $this->member_model->checkUserKeyRegist($keyregist,$user);
		if ($check){
			$ref = $this->member_model->updateUserRegistFinish($keyregist,$user);
			if ($ref){
				//finish regist
				$err['noterror']="<div class=noterror> Configuration you regist finish ! </div>";
				$this->my_layout->view('html/registfinish',$err);
			}else{
				//not finist regist because update db
				$err['error']="<div class=error> Error save data to db, Please try again </div>";
				$this->my_layout->view('html/registerror',$err);
			}
		}else{
			$data['error'] = '<div class=error>Links regist false, Please confirm admin abc@gmail.com</div>';
			$this->my_layout->view('html/registerror',$data);
		}
	}
	public function sendmail_smtp($data = null ,$que = null){

		$this->load->library('email');

		$config['protocol'] = 'smtp';
		$config['smtp_host'] = 'mail.sagaco.com.vn';
		$config['smtp_port'] = '25';
		$config['smtp_timeout'] = '5';
		$config['smtp_user'] = 'admin@sagaco.com.vn';
		$config['smtp_pass'] = 'Thanh_Admin';//'119thanh782';
		$config['charset'] = 'utf-8';
		$config['wordwrap'] = TRUE;

		$this->email->initialize($config);

		$this->email->from('nvthanhdhkhtn@gmail.com', 'Sagaco');
		if (1==$que){//send mail phuc hoi mat khau
			$this->email->subject('Email Recover Info');
//			$this->email->to($data['email']);
			$this->email->set_newline("\r\n");
			$this->email->message(" Hi ".$data['user_id']."
			you received this email because you forgot pass and id to login at website ".base_url()." 
			your new password is : 12345678 
			user id is : ".$data['user_id']);
		}elseif (2==$que) {//send mail dang ky thanh vien
			$this->email->to('nvthanhdhkhtn@gmail.com');

			$this->email->subject('Email Register');
			$this->email->set_newline("\r\n");
			$this->email->set_newline("\r\n");
			$this->email->message('Dear admin !
			Phone: '.$data['phone'].'
			Email: '.$data['email'].'
			User '.$data["user_id"].' want to become member of sagaco website
			if you accept then click links follow '.base_url().'welcome/confirmRegist/'. $data["key_regist"].'/'.$data['user_id']);
		}else{
			return false;
		}
		if($this->email->send())
			return true;
		return false;
		//		echo $this->email->print_debugger();
	}
	public function getCatSubId($ref =NULL){
		if ($this->checkLogin()){
			$data = $this->member_model->showDetailIdMember($ref);
			$setview = $data[0];
			$setview['relation'] = $this->member_model->showRelationIdMember($ref);
			$this->my_layout->view('member/newdesign',$setview);
		}else{
			$data['error'] = '<div class=error>Please, Login to view products </div>';
			$this->my_layout->view('html/login',$data);
		}
	}

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */